// Copyright (C) 2024 wlly-lzh
// Created by wlly-lzh on 24-4-9
// 公用的双链表
#ifndef _DOUBLYLINKEDLIST_C
#define _DOUBLYLINKEDLIST_C

#include <stdlib.h>

typedef struct DLinkedList DLinkedList;
struct DLinkedList { // Doubly Linked List
	DLinkedList *TheLast;
	void *Data;
	DLinkedList *TheNext;
};
void Destroy_DLinkedList(DLinkedList *List,void (*FreeData)(void *)){
	DLinkedList * Del=List;
	while(List != NULL){
		List=Del->TheNext;
		(*FreeData)(Del->Data);
		free(Del);
		Del=List;
	}
}
// 1 2 3 4 5 6 7 8 9
//       ^         ^
void Insert_DLinkedList(DLinkedList *List,unsigned int addr,void *Data){
	for(unsigned int i=1;i < addr-1; ++i){
		List=List->TheNext;
	}
	DLinkedList *addList=(DLinkedList *)malloc(sizeof(DLinkedList));
	if(addList == NULL){
		printf("liblds: malloc false!\n");
		exit(3);
	}
	addList->Data=Data;             // 初始化addList
	addList->TheLast=List;
	addList->TheNext=List->TheNext;
	List->TheNext=addList;          // 更新上一个节点
	if(addList->TheNext != NULL){   // 更新下一个节点
		(addList->TheNext)->TheLast=addList;
	}
}
// 1 2 3 4 5
// 
void GetItem_DLinkedList(DLinkedList *List,unsigned int addr,void **Data){
	for(unsigned int i=1; i<addr; ++i){
		List=List->TheLast;
	}
	*Data=List->Data;
}
void Delete_DLinkedList(DLinkedList *List,unsigned int addr,void (*FreeData)(void*)){
	for(unsigned int i=1; i<addr; ++i){
		List=List->TheNext;
	}
	DLinkedList * Del=List;
	Del->TheLast->TheNext=List->TheNext;
	Del->TheNext->TheLast=List->TheLast;
	FreeData(Del->Data);
	free(Del);
}
#endif // _DOUBLYLINKEDLIST_C
